const { resolve } = require('path')

const { User } = require(resolve(__dirname, '../database/dbModule/login'))

const {
  jgcl,
  passwordEncryption,
  passwordVerify,
  createToken
} = require(resolve(__dirname, '../utils/utils'))

// 登录处理函数
const login = async (ctx) => {
  const { username, password } = ctx.query
  try {
    const findRes = await User.findOne({ username })
    if (findRes === null) {
      jgcl(ctx, 204, '登录失败，用户不存在')
    } else {
      // 密码验证
      const res = passwordVerify(password, findRes.password)
      if (res) {
        const newRes = findRes
        newRes.password = ''
        // 生成token
        const token = createToken(newRes)
        jgcl(ctx, 200, '登录成功', { info: newRes, token: 'Bearer ' + token })
      } else {
        jgcl(ctx, 205, '密码错误', { username: findRes.username })
      }
    }
  } catch (error) {
    jgcl(ctx, 203, '登录失败', error)
  }
}

// 注册
const enroll = async (ctx) => {
  let { username, password, eMail } = ctx.request.body

  try {
    // 密码加密
    const passwordRes = passwordEncryption(password)
    password = passwordRes

    // 数据库中搜索用户名
    const findRes = await User.findOne({ username })
    if (findRes !== null) {
      jgcl(ctx, 202, '用户已存在', { username: findRes.username })
    } else {
      // 将用户添加到数据库
      const res = await User.create({
        username,
        password,
        eMail,
        createTime: new Date().getTime(),
        isBlogger: false,
        isDel: false
      })
      jgcl(ctx, 200, '注册成功', { username: res.username })
    }
  } catch (err) {
    jgcl(ctx, 201, '注册失败', { err: err.message })
  }
}



module.exports = {
  login,
  enroll,
}